﻿namespace CSP.Utils

module ListMap =

    open System.Collections.Generic

    /// A mutable dictionary with lists as values.
    type internal ListMap<'k,'a> when 'k: comparison = ListMap of Dictionary<'k, 'a list>  * ('a -> 'k)

    /// Creates an empty ListMap.
    let internal empty getKey = ListMap (new Dictionary<_,_>(), getKey)

    /// Adds a value to a ListMap.
    let internal add value (ListMap (map, getKey)) =
        let key = getKey value
        let l = match map.TryGetValue(key) with
            | false, _ -> [value]
            | true, l' -> value :: l'
        map.[key] <- l

    /// Looks up a key in a ListMap, returns all values and removes them.
    let internal findAndRemove key (ListMap (map, getKey)) =
        match map.TryGetValue(key) with
            | false, _ -> []
            | true, l -> map.Remove(key) |> ignore; l